package dbservlet;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class Haha extends HttpServlet{
	private static final long serialVersionUID = 1L;
	//dopost方法
	public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		String methodName=request.getParameter("tiaozhuan");
		int method=Integer.parseInt(methodName);
		try{
			switch(method){
		      case 0:
			        insert(request,response);
		     /* case 1:
		    	    difpage(request,response);*/
		    	    break;
			}
		}catch (ClassNotFoundException e){
			e.printStackTrace();
		}catch (SQLException e){
			e.printStackTrace();
		}
	}
	//doGet方法
	public void doGet(HttpServletRequest request,HttpServletResponse response)
		      throws ServletException,IOException{
		doPost(request,response);
	}
	
	//数据库的连接方法
	public Connection connect() throws ClassNotFoundException,SQLException{
		Connection conn=null;
		Class.forName("com.mysql.jdbc.Driver");
		String url="jdbc:mysql://localhost:3306/ProduceMyself";
		String user="root";
		String password="root";
		conn=DriverManager.getConnection(url,user,password);
		return conn;
	}
	//关闭数据库资源
	public void close(Statement stat,Connection conn) throws SQLException{
		if(stat!=null){
			stat.close();
		}
		if(conn!=null){
			conn.close();
		}
	}
	
	//插入方法
	public void insert(HttpServletRequest request, HttpServletResponse response) throws SQLException, ClassNotFoundException, ServletException, IOException{
		Connection conn=null;
		Statement stat=null;
		conn = connect();
		stat = conn.createStatement();
		int No=Integer.parseInt(request.getParameter("No"));
		String name=request.getParameter("name");
		String pass=request.getParameter("pass");
		String hangye = request.getParameter("hangye");
		String sex = request.getParameter("sex");
		String[] aihao= request.getParameterValues("change");
		stat.execute("insert into MyselfInfo(No,name,pass,hangye,sex,aihao) " +
				"values("+No+",'"+name+"','"+pass+"','"+hangye+"','"+sex+"','"+aihao+"')") ;
		 close(stat,conn);
		 request.setCharacterEncoding("utf-8");
		 response.setCharacterEncoding("utf-8");
		 request.getRequestDispatcher("Addindex.jsp").forward(request, response);
	}
	
	

}
